package org.bao.pet.tools;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.bao.pet.image.ImageReader;
import org.bao.pet.utils.FileSystem;
import org.bao.pet.utils.PlatformInfo;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Resizer {
	private int height = 0;
	private int width = 0;
	private String filepath = null;
	private Image image = null;
	
	public void config(String filepath,int height,int width){
		this.filepath = filepath;
		ImageReader ir = new ImageReader(this.filepath);
		
		this.image = ir.getImage();
		
		if(this.image.getHeight(null) < this.image.getWidth(null)){
			this.height = width;
			this.width = height;
		}
		else{
			this.height = height;
			this.width = width;
		}
	}
	
	public void config(String filepath,int factor){
		this.filepath = filepath;
		ImageReader ir = new ImageReader(this.filepath);
		
		this.image = ir.getImage();
		
		this.height = this.image.getHeight(null);
		this.width = this.image.getWidth(null);
		
		if(factor > 0){
			this.height *= (-1 * factor);
			this.width *= (-1 * factor);
		}
		else
		if(factor < 0){
			this.height /= (-1 * factor);
			this.width /= (-1 * factor);
		}
	}
	
	public void zoom(){
		try {
			BufferedImage bi = new BufferedImage(this.width,this.height,BufferedImage.TYPE_INT_RGB);
			
			bi.getGraphics().drawImage(this.image,0,0,this.width,this.height,null);
			
			File parent = FileSystem.createDirectory(new File(FileSystem.getUpperDirectory(this.filepath)), FileSystem.NEW_DIRECTORY_NAME_DEFAULT);
			String newFilepath = parent.getAbsolutePath() + PlatformInfo.getInstance().get(PlatformInfo.INFO_TYPE_SEPARATOR) + FileSystem.generateNewFileName(this.filepath);
			
			FileOutputStream fos = new FileOutputStream(newFilepath);
			
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
			encoder.encode(bi);
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ImageFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
